/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package metro.jme.lottery.graphics.screens;

import java.util.Vector;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.ChoiceGroup;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.ItemCommandListener;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextField;
import javax.microedition.lcdui.Ticker;
import metro.jme.lottery.persist.FavBean;
import metro.jme.lottery.persist.Persist;
import metro.jme.lottery.persist.SetBean;
import metro.jme.lottery.main.LotteryMIDlet;

/**
 *
 * @author pierre
 */
public class EditFavScreen extends Form implements CommandListener, ItemCommandListener {

	// Commands
	private Command m_backCmd;
	private Command m_saveCmd;
	private Command m_addCmd;
	private Command m_returnCmd;
	// Member attributes
	private Vector m_fields;
	private Ticker m_ticker;
	private ChoiceGroup m_choiceGroup;
	private LotteryMIDlet m_lm;

	public EditFavScreen(String title, LotteryMIDlet lm) {
		super(title);
		m_lm = lm;
		m_backCmd = new Command("Back", Command.BACK, 1);
		m_saveCmd = new Command("Save", Command.SCREEN, 1);
		m_addCmd = new Command("Add", Command.SCREEN, 1);
		m_returnCmd = new Command("Return", Command.SCREEN, 1);
		this.addCommand(m_backCmd);
		//this.addCommand(m_saveCmd);
		this.addCommand(m_addCmd);

		// Create all ellements of the screen
		init();
	}

	/**
	 * Init method, create all elements in the form
	 */
	public final void init() {

		// First, we populate the fields by fecthing data from RS
		fetchFavSet();
		TextField tf;
		for (int i = 0; i < m_fields.size(); i++) {
			tf = (TextField) m_fields.elementAt(i);
			this.append(tf);
		}

		// Create the choice group
		String[] setsLabels = new String[m_fields.size()];
		for (int i = 0; i < m_fields.size(); i++) {
			setsLabels[i] = "Set no:" + (i + 1);
		}

		m_choiceGroup = new ChoiceGroup("Select your favourite set", ChoiceGroup.EXCLUSIVE, setsLabels, null);
		m_choiceGroup.setSelectedIndex(FavBean.getFavIndex(), true);
		this.append(m_choiceGroup);

		StringItem st = new StringItem("", "Save", StringItem.BUTTON);
		st.addCommand(m_saveCmd);
		st.setItemCommandListener(this);
		st.setDefaultCommand(m_saveCmd);
		this.append(st);

		// Create the ticker
		m_ticker = new Ticker("Select your favourite set, and save them");
		this.setTicker(m_ticker);
	}

	/**
	 * Get the stored data and create the form so it will display every existing
	 * data in the RMS
	 */
	private void fetchFavSet() {
		// Read from RMS, if some record are found
		// If not, then create a new text field, otherwyse, create one for each record, and a blank one
		String[] storedData = Persist.getSets();
		m_fields = new Vector();
		for (int i = 0; i < m_fields.size(); i++) {
			System.out.println("m_fi = " + m_fields.elementAt(i));
		}
		if (storedData == null) {
			System.err.println("No data found");
		} else {
			System.out.println("data found");
			// If data found, add a new text field for each row
			for (int i = 0; i < storedData.length; i++) {
				m_fields.addElement(new TextField("Set : ", storedData[i], 256, TextField.ANY));
			}
		}
		TextField tf = new TextField("Set : ", "", 1024, TextField.ANY);
		m_fields.addElement(tf);
	}

	/**
	 * Store everything before leaving the page
	 */
	private boolean saveContext() {
		try {
			saveSets();
			saveFav();
		} catch (Exception e) {
			//Display an alert showing storage didn't work
			Alert al = new Alert("Storage error", "Check the format of the set, should be \"# # # #\"", null, AlertType.WARNING);
			al.setTimeout(Alert.FOREVER);
			al.addCommand(m_returnCmd);
			al.setCommandListener(this);
			m_lm.displayNewScreen(al);
			return false;
//			EditFavScreen efv = new EditFavScreen("Edit your saved number sets", m_lm);
//			m_lm.displayNewScreen(efv);
//			efv.setCommandListener(efv);
		}
		return true;
	}

	/**
	 * Store all sets
	 */
	private void saveSets() throws Exception {
		TextField element;
		String[] content = new String[m_fields.size()];
		for (int i = 0; i < m_fields.size(); i++) {
			element = (TextField) m_fields.elementAt(i);
			content[i] = element.getString();
			System.out.println("content = " + content[i]);
		}
		Persist.store(content);
		
	}

	/**
	 * Store the favourite set
	 */
	private void saveFav() {
		int selected = m_choiceGroup.getSelectedIndex();
		FavBean.store(selected);
	}

	/**
	 * Get the numbers of items in the form
	 * @return 
	 */
	private int getTotalNumberOfElements() {
		// We add 1 because of the choicegroup, actually we don't :p
		return m_fields.size();
	}

	/**
	 * Add a new Textfield to the form
	 */
	private void addNewField() {
		m_fields.addElement(new TextField("Set : ", "", 64, TextField.ANY));
		// Last element is the choice group, so get the total of element, and insert before
		this.insert(getTotalNumberOfElements() - 1, (TextField) m_fields.lastElement());
		// Delete the choice groupe, add a new entry in it, and add it again.		
		this.addNewChoice();
	}

	/**
	 * Add a new choice element to the form
	 */
	private void addNewChoice() {
		this.delete(this.size() - 1);
		// Create the choice group
		String[] setsLabels = new String[m_fields.size()];
		for (int i = 0; i < m_fields.size(); i++) {
			setsLabels[i] = "Set no:" + (i + 1);
		}
		m_choiceGroup = m_choiceGroup = new ChoiceGroup("Select your favourite set", ChoiceGroup.EXCLUSIVE, setsLabels, null);
		this.append(m_choiceGroup);
	}

	/**
	 * CommandListener Method
	 * @param cmnd
	 * @param dsplbl 
	 */
	public void commandAction(Command cmnd, Displayable dsplbl) {
		if (cmnd == m_backCmd) {
			m_lm.back();
		} else if (cmnd == m_addCmd) {
			addNewField();
		} else if (cmnd == m_returnCmd) {
			m_lm.displayNewScreen(this);
		}
	}

	public void commandAction(Command cmnd, Item item) {
		if (cmnd == m_saveCmd) {
			if (saveContext())
				m_lm.back();
		}
	}
}
